<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\facade\Db;

class Taskcount extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\Todaycount();
    }



    /**
     * 按天统计对应的出单(已支付订单)
     */
    public  function today_count()
    {
        //删除数据表中的数据
        // $start_time = strtotime(date('Y-m-1') . ' 00:00:00');
        $start_time = strtotime('-2 days');
        $end_time = time();
        //删除本月数据重新更新
        $where_delete[] = ['order_time', '>', date('Y-m-d H:i:s', $start_time)];
        $where_delete[] = ['order_time', '<', date('Y-m-d H:i:s', $end_time)];
        table('todaycount')->where($where_delete)->delete();

        $sql = "SELECT 
        c.sku,
        b.quantity,
        -- sum(b.quantity) as count,
        -- DATE_FORMAT(FROM_UNIXTIME(a.created_at),'%Y-%m-%d') as timedate,
        b.product_id,
        c.variants_id,
        a.created_at
        FROM qu_order as a
        LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
        LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
        -- LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
        where a.financial_status = 'paid'
        AND a.created_at >= " . $start_time . "
        AND a.created_at <= " . $end_time . "
        AND c.sku is not null
        AND b.quantity > 0
        ORDER BY a.created_at DESC
        ";
        //    ORDER BY count
        // sha02-beige+black-XL-1
        $join_datas = Db::query($sql);
        // halt($join_datas);
        if (!$join_datas) {
            return [];
        }
        // halt($join_datas);
        foreach ($join_datas as  $v) {
            // file_put_contents('sku1111.txt', $v['sku']);
            // halt($v['sku']);
            // sha02-beige+black-XL-1
            $multiple = 1;
            if (strpos(trim($v['sku']), '-') !== false) {
                $explode_arr = explode('-', $v['sku']);
                if (isset($explode_arr[3])) {
                    $multiple = $explode_arr[3];
                }
                if (isset($explode_arr[1]) && strpos($explode_arr[1], '+') !== false) {
                    try {
                        $color_arr  = explode('+', $explode_arr[1]);
                        //循环插入多条数据
                        foreach ($color_arr as   $color_v) {
                            //多个颜色循环插入数据表
                            $sku = $explode_arr[0] . '-' . $color_v . '-' . $explode_arr[2];
                            $insert_data = [
                                'brand' => !empty($explode_arr[0]) ? $explode_arr[0] : '',
                                'sku' => $sku,
                                'count' =>  $v['quantity'] * $multiple,
                                'product_id' => $v['product_id'],
                                'sku_id' => $v['variants_id'],
                                'order_time' => date('Y-m-d H:i:s', $v['created_at']),
                                'update_time' => date('Y-m-d H:i:s', time()),
                            ];
                            table('todaycount')->insert($insert_data);
                        }
                    } catch (\Exception $e) {
                        continue;
                    }
                } else if (isset($explode_arr[1]) && strpos($explode_arr[1], '+') === false) {
                    try {
                        //单个颜色循环插入数据表
                        $sku = $explode_arr[0] . '-' . $explode_arr[1] . '-' . $explode_arr[2];
                        $insert_data = [
                            'brand' => !empty($explode_arr[0]) ? $explode_arr[0] : '',
                            'sku' => $sku,
                            'count' =>  $v['quantity'] * $multiple,
                            'product_id' => $v['product_id'],
                            'sku_id' => $v['variants_id'],
                            'order_time' => date('Y-m-d H:i:s', $v['created_at']),
                            'update_time' => date('Y-m-d H:i:s', time()),
                        ];
                        table('todaycount')->insert($insert_data);
                    } catch (\Exception $e) {
                        continue;
                    }
                }
            }
        }
    }



    /**
     * 
     * 查询出入库表处理每个编号的出入库详情
     * 
     */


    public function count()
    {
        $output_list = table('output')->field('id,brand')->select()->toarray();
        foreach ($output_list as $v) {
            $this->deal_count($v);
        }
    }
    /**
     * 按天统计对应的出单(已支付订单)
     */
    public  function deal_count($output)
    {
        $brand_name = strtolower($output['brand']);
        $start_time = strtotime(date('Y-m-1') . '00:00:00');
        $end_time = strtotime(date('Y-m-1') . '23:59:59');
        $sql = "SELECT 
        c.sku,
        sum(b.quantity) as count,
        b.title,
        e.handle_url,
        b.product_id,
        c.variants_id as SKUid
        FROM qu_order as a
        LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
        LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
        LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
        where a.financial_status = 'paid'
        AND a.created_at >= " . $start_time . "
        AND a.created_at <= " . $end_time . "
        AND c.id > 1
        AND b.sku like '%{$brand_name}%'
        GROUP BY SKUid
        ORDER BY count DESC
    ";
        $join_datas = Db::query($sql);
        if (!$join_datas) {
            return [];
        }
        foreach ($join_datas as $k => $v) {
            $explode_arr = explode('-', strtolower($v['sku']));
            if (isset($explode_arr[1])) {
                $color[$k] = explode('+', $explode_arr[1]);
            }
        }
        foreach ($join_datas as $k => $v) {
            $explode_arr = explode('-', strtolower($v['sku']));
            if (isset($explode_arr[2])) {
                $size[$k] = $explode_arr[2];
            }
        }
        $color = $this->array_unique_fb($color);
        $size = array_values(array_unique($size));
        $merge_sku[$brand_name] = 0;
        foreach ($color as   $v) {
            $merge_sku[$brand_name . '_' . $v] = 0;
            foreach ($size as $vl) {
                $merge_sku[$brand_name . '_' . $v . '_' . $vl] = 0;
            }
        }
        foreach ($join_datas as $join_data) {
            //数量
            $multiple = 1;
            $sku_title_arr =  explode('-', strtolower($join_data['sku']));
            // file_put_contents('sku.txt', $join_data['sku']);
            if (isset($sku_title_arr[0])) {
                if (isset($sku_title_arr[1])) {
                    if (isset($sku_title_arr[3])) {
                        $multiple = $sku_title_arr[3];
                    }
                    $sku_title_arr1 =  explode('+', $sku_title_arr[1]);
                    foreach ($sku_title_arr1 as $vl) {
                        $merge_sku[$sku_title_arr[0]] = $merge_sku[$sku_title_arr[0]] + ((int)$join_data['count']) * $multiple;
                        $merge_sku[$sku_title_arr[0] . '_' . $vl] = $merge_sku[$sku_title_arr[0] . '_' . $vl] + ((int)$join_data['count']) * $multiple;
                        if (isset($sku_title_arr[2])) {
                            $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]] = $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]]  + ((int)$join_data['count']) * $multiple;
                        }
                    }
                }
            }
        }

        foreach ($merge_sku as $k => $v) {
            if ($v == 0) {
                unset($merge_sku[$k]);
            }
        }
        halt($merge_sku);
        $merge_sku_new = array();
        foreach ($merge_sku as $k => $v) {
            $merge_sku_new[] =
                ['sku' => $k, 'count' => $v];
        }
        halt($merge_sku_new);
    }

    /**
     * 去掉重复的值
     */
    public function array_unique_fb($array2D)
    {
        foreach ($array2D as $k => $v) {
            $v = join(',', $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[$k] = $v;
        }
        $temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
        $temp = implode(',', $temp);
        $temp = explode(',', $temp);
        return  array_unique($temp);
    }
}
